package com.xrui.hbaseview.ui.forms;

import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.uiDesigner.core.GridLayoutManager;
import com.xrui.hbaseview.config.ConnectionDetails;
import com.xrui.hbaseview.config.GlobalConfig;
import com.xrui.hbaseview.hbase.ConnectionManager;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Map;

public class ConnectionDetailsDialog extends JDialog {

    //region Variables
    private static final long serialVersionUID = 4254076848011995814L;

    private JPanel contentPane;
    private JButton buttonConnect;
    private JButton buttonCancel;
    private JComboBox clusterName;
    private ConnectionDetails connectionDetails;

    //region Constructor
    public ConnectionDetailsDialog() {
        setContentPane(this.contentPane);
        setModal(true);
        setTitle("Connect to an HBase cluster...");
        getRootPane().setDefaultButton(this.buttonConnect);

        Map<String, String> clusters = GlobalConfig.instance().getClusterConfigurations();
        for (String cluster : clusters.keySet()) {
            clusterName.addItem(cluster);
        }

        if (clusterName.getSelectedItem() == null) {
            this.buttonConnect.setEnabled(false);
        }

        this.clusterName.addItemListener(
            e -> {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    this.buttonConnect.setEnabled(true);
                }
                if (e.getStateChange() == ItemEvent.DESELECTED) {
                    this.buttonConnect.setEnabled(false);
                }
            });
        this.buttonConnect.addActionListener(
            e -> onOK());

        this.buttonCancel.addActionListener(
            e -> onCancel());

        // call onCancel() when cross is clicked
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(
            new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    onCancel();
                }
            });

        // call onCancel() on ESCAPE
        this.contentPane.registerKeyboardAction(
            e -> onCancel(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    }

    //region Public Methods
    public boolean showDialog(Component owner) {
        this.setComponentOrientation(owner.getComponentOrientation());
        this.pack();
        this.setResizable(false);
        this.setLocationRelativeTo(owner);
        this.setVisible(true);

        return this.connectionDetails != null;
    }
    //endregion

    public ConnectionDetails getConnectionDetails() {
        return this.connectionDetails;
    }

    //region Private Methods
    private void onOK() {
        String cluster = ConnectionDetailsDialog.this.clusterName.getSelectedItem().toString();
        if (cluster == null || cluster.isEmpty()) {
            return;
        }
        this.connectionDetails = new ConnectionDetails(cluster);

        this.contentPane.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

        boolean canConnect;

        try {
            canConnect = this.connectionDetails.canConnect();
        } finally {
            this.contentPane.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
        }

        if (canConnect) {
            dispose();
        } else {
            JOptionPane.showMessageDialog(
                ConnectionDetailsDialog.this,
                "Failed to connect to hbase.\n\nMake sure you have access to all hadoop nodes.",
                "Connection failed...", JOptionPane.ERROR_MESSAGE);

            ConnectionManager.get().release(connectionDetails);
            connectionDetails = null;
        }
    }

    //endregion

    private void onCancel() {
        dispose();
    }

    {
// GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE!
        $$$setupUI$$$();
    }

    /**
     * Method generated by IntelliJ IDEA GUI Designer
     * >>> IMPORTANT!! <<<
     * DO NOT edit this method OR call it in your code!
     *
     * @noinspection ALL
     */
    private void $$$setupUI$$$() {
        contentPane = new JPanel();
        contentPane.setLayout(new GridLayoutManager(2, 1, new Insets(10, 10, 10, 10), -1, -1));
        final JPanel panel1 = new JPanel();
        panel1.setLayout(new GridLayoutManager(2, 2, new Insets(5, 0, 0, 0), -1, -1));
        contentPane.add(panel1, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, 1, null, null, null, 0, false));
        final JPanel panel2 = new JPanel();
        panel2.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1));
        panel1.add(panel2, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_VERTICAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
        buttonConnect = new JButton();
        buttonConnect.setText("Connect");
        panel2.add(buttonConnect, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        buttonCancel = new JButton();
        buttonCancel.setText("Cancel");
        panel2.add(buttonCancel, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        final JSeparator separator1 = new JSeparator();
        panel1.add(separator1, new GridConstraints(0, 0, 1, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false));
        final JPanel panel3 = new JPanel();
        panel3.setLayout(new GridLayoutManager(2, 2, new Insets(0, 0, 0, 0), -1, -1));
        contentPane.add(panel3, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, new Dimension(300, -1), null, 0, false));
        final JLabel label1 = new JLabel();
        label1.setText("Hadoop Cluster Name:");
        panel3.add(label1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        clusterName = new JComboBox();
        panel3.add(clusterName, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
    }

    /**
     * @noinspection ALL
     */
    public JComponent $$$getRootComponent$$$() {
        return contentPane;
    }
}
